package com.java.actual.chatroom;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;

public class ChatRoomServer {
	private ServerSocket ss;
	private HashSet<Socket> allSockets;
	
	public ChatRoomServer(){
		try {
			ss=new ServerSocket(8888);
			allSockets=new HashSet<Socket>();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void startService()throws IOException{
		while(true){
			Socket s=ss.accept();
			allSockets.add(s);
			new ServerThread(s).start();
		}
	}
	
	private  class ServerThread extends Thread{
		private Socket s;
		
		public ServerThread(Socket s){
			this.s=s;
		}
		
		public void run(){
			//??????
			BufferedReader br=null;
			
			try {
				br=new BufferedReader(new InputStreamReader(s.getInputStream()));
				
				while(true){
					String str=br.readLine();
					if(str.indexOf("%EXIT%")==0){
						allSockets.remove(s);
						sendMessageToAllClient(str.split(":")[1]+"离开了聊天室！！");
						s.close();
						break;
					}
					sendMessageToAllClient(str);
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		public void sendMessageToAllClient(String message){
			Date date=new Date();
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				System.out.println(message+"\t["+sdf.format(date)+"]");
				for(Socket s:allSockets){
					PrintWriter pw=new PrintWriter(s.getOutputStream());
					pw.println(message+"\t["+sdf.format(date)+"]");
					pw.flush();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}

	
	public static void main(String[] args){
		try {
			new ChatRoomServer().startService();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
